package learnjava.concur.chapter4;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {

    /**
     * 测试ReentrantLock的多重条件
     */
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {

        Condition ciga = lock.newCondition(); //烟
        Condition food = lock.newCondition(); //饭

        new Thread(()->{
            try {
                lock.lock();
                try {
                    System.out.println("t1:没烟就等");
                    ciga.await();
                    System.out.println("t1:有烟干活");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                lock.unlock();
            }
        }).start();

        new Thread(()->{
            try {
                lock.lock();
                try {
                    System.out.println("t2:没饭就等");
                    food.await();
                    System.out.println("t2:有饭干活");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                lock.unlock();
            }
        }).start();

        try {
            System.out.println("main:睡一会再给t1送烟");
            Thread.sleep(2*1000);
            lock.lock();
            ciga.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

        try {
            System.out.println("main:睡一会再给t2送饭");
            Thread.sleep(2*1000);
            lock.lock();
            food.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
